<?php
namespace app\index\controller\miniapp;
use think\Controller;
use app\index\common;
use think\Db;

use think\Session;
use think\Request;
use app\index\controller\Log\InsertLog as IL;
use app\index\controller\Log\OperationLog as OL;
use app\index\controller\Dropdown;
use think\Paginator;
use think\Config;



class Order extends Controller
{
     /**
     * 2018-08-15
     * 
     * 刘家腾
     * 
     * 小程序订单列表 基础SQL where
     *
     * @param      string  $data      The data
     * @param      string  $field_data  The field_data
     * @param      string  $page     The page
     * @param      string  $singlepage     The singlepage
     */
    public function list_sql($data='',$field_data='',$page='',$singlepage='')
    {
        
       $product_data = Db::table('orders')->alias('or')
                    ->join('users ui','or.user_id=ui.id','LEFT')
                    ->join('orders_info oi','or.batchcode=oi.batchcode','LEFT')
                    ->join('sales_condition sc','or.status=sc.id','LEFT')
                    ->join('sales_plateform sp','or.sale_system = sp.id','LEFT')
                    ->Distinct(true)
                    ->where($data)
                    ->field($field_data)
                    ->order('or.createtime desc')
                    ->paginate($singlepage,false,['query'=>request()->param()])
                    ->toArray();
       // $product_data['sql'] =Db::table('orders')->getLastSql();
       return $product_data;
    }

    public function orders_info_sql($data='',$field_info='')
    {
       $orders_infos = Db::table('orders_info')->alias('or')
                    ->join('store s','or.store_id=s.user_id','LEFT')
                    ->join('product p','or.product_id=p.id','LEFT')
                    ->join('systematics stt', 'p.brand_id = stt.id', 'LEFT') //品牌
                    ->join('systematics sy', 'p.systematics_id = sy.id', 'LEFT') //系列
                    ->join('product_fineness pf','p.product_condition = pf.id','LEFT')
                    ->join('perchase_source ps','p.procurement_status = ps.id','LEFT')
                    ->join('user_info ui','or.user_id=ui.user_id','LEFT')
                    ->join('users u','or.user_id=u.id','LEFT')
                    ->join('staff st','or.staff_id=st.user_id','LEFT')
                    ->join('shipping_mode sm','or.shipping_code=sm.id','LEFT')
                    ->join('sales_condition sc','or.status=sc.id','LEFT')
                    ->join('delivery dv','or.delivery_id=dv.id','LEFT')
                    ->where($data)
                    ->where('or.state',0)
                    ->field($field_info) 
                    ->select();     
       $orders_info = collection($orders_infos)->toarray();
       return $orders_info;
    }
                    
    /**
     * 2018-08-15
     * 
     * 刘家腾
     * 
     * 小程序订单列表
     */
    public function list(Request $request)
    {
        $postData = $request->post();
        $user_info=Session::get('user');
        $data=array();
        $singlepage=20;
        $page = 1;
        $business_id=$this->business_id;
        $data['or.business_id']  = array('eq',$business_id);//商户
        $data['or.state']  = array('eq',0);//启用
        $data['or.type']  = array('in','3,4');//小程序
        if( !empty($postData['singlepage']) ){
            $singlepage  = $postData['singlepage'];
        }
        if( !empty($postData['batchcode']) ){
            $data['or.batchcode']  = array('eq',$postData['batchcode']);
        }
        if( !empty($postData['phone']) ){
            $data['ui.phone']  = array('eq',$postData['phone']);
        }
        
        if( !empty($postData['status']) ){
            $data['or.status']  = array('eq',$postData['status']);
        }
        if( !empty($postData['payment_status']) ){
            $data['oi.payment_status']  = array('eq',$postData['payment_status']);
            $data_info['or.payment_status']  = array('eq',$postData['payment_status']);
        }
        if( !empty($postData['page']) ){
            $page = $postData['page'];
        }
        if( !empty($postData['shipping_sn']) ){
            $data['oi.shipping_sn']  = array('eq',$postData['shipping_sn']);
        }
        
        $field_data = 'or.remark,or.id,or.batchcode,or.uniqueOrderNo pay_batchcode,or.transaction_id,or.user_id,or.total_price,or.total_rebate,or.total_fare,or.coupon_id,or.coupon_price,or.payment_status,or.status,or.last_time,or.createtime,or.pay_time,or.rights_time,or.refund_time,or.remark,or.consignee,or.delivery_id,or.is_urgent,or.urgent_remark,or.cover,or.order_source,or.sale_system,sc.value status_value,sp.value system_value,ui.phone,ui.name';

        $field_info ='or.remark,stt.title brand_title,sy.title systematics_title,or.id,or.peer_price,or.business_id,or.store_id,or.user_id,or.batchcode,or.pay_batchode,or.info_batchcode,or.product_id,or.product_name,or.coupon_id,or.express_id,or.price,or.cost_price,or.fare,or.status,or.pequired_points,or.quantity,or.pay_reatetime,or.rights_time,or.refund_time,or.last_time,or.payment_status,or.createtime,or.remark,or.is_prepay,or.deposit,or.shipping_sn,or.sale_date,or.nursing_fee,or.other_fee,or.staff_id,or.nursing_cost,or.nursing_income,or.nursing_condition,or.nursing_remark,or.customer_name,or.customer_id,or.is_urgent,or.urgent_remark,or.cover,or.order_source,or.is_confirm,or.finance_confirm_time,or.parts,or.is_settlement,or.is_nursing,or.procurement_status,or.settlement_time,p.product_name,p.full_name,p.product_sn,p.product_condition,pf.value product_condition_value,p.procurement_status, ps.value procurement_value,p.cost_price,p.pic_url,p.is_synchro,p.is_autodeliver,st.name staff_name,p.additional,p.systematics_id,st.name,p.product_source,p.sale_share,p.receive_share,s.store_name,sm.shipping_name,sc.value status_value,dv.name delivery_name, dv.phone delivery_phone, dv.province delivery_province,dv.city delivery_city,dv.district delivery_district, dv.address delivery_address';

        $datas=$this->list_sql($data,$field_data,$page,$singlepage);
        if ( empty($datas['data']) ) {
            return ['code' => 666, 'msg' => "没有查询到类似数据！", 'data' => null];
        }
        foreach ($datas['data'] as $key => $value) {
            $data_info['or.batchcode']  = array('eq',$value['batchcode']);
            $datas['data'][$key]['product_data']=$this->orders_info_sql($data_info,$field_info);
            $datas['data'][$key]['quantity'] = count( $datas['data'][$key]['product_data']);
            $datas['data'][$key]['real_income']=round(($value['total_price']-$value['coupon_price']),2);
        }
        return ['code' => 666, 'msg' => "查询成功！", 'data' => $datas];
    }

    /**
     * 2018-08-15
     * 
     * 刘家腾
     * 
     * 发货 基础SQL where
     *
     * @param      string  $data      The data
     * @param      string  $field_data  The field_data
     * @param      string  $page     The page
     * @param      string  $singlepage     The singlepage
     */
    public function deliver_sql($data='',$field_data='',$page='',$singlepage='')
    {
        
       $product_data = Db::table('orders')->alias('or')
                    ->join('orders_info oi','or.batchcode=oi.batchcode','LEFT')
                    ->join('sales_condition sc','or.status=sc.id','LEFT')
                    ->join('sales_plateform sp','or.sale_system = sp.id','LEFT')
                    ->Distinct(true)
                    ->where($data)
                    ->field($field_data)
                    ->paginate($singlepage,false,['query'=>request()->param()])
                    ->toArray();
       return $product_data;
    }              
    /**
     * 2018-08-15
     * 
     * 刘家腾
     * 
     * 发货
     */
    public function deliver(Request $request)
    {
        $postData = $request->post();
        $user_info=Session::get('user');
        $business_id=$this->business_id;
        $where['business_id']  = array('eq',$business_id);
        $where['state']  = array('eq',0);

        if( empty($postData['batchcode']) ){
            return ['code' => 30051, 'msg' => "订单号不能为空！", 'data' => 'batchcode'];
        }
        $where['batchcode']  = array('eq',$postData['batchcode']);
        $whereinfo['batchcode']  = array('eq',$postData['batchcode']);
        if( empty($postData['info_batchcode']) ){
            return ['code' => 30052, 'msg' => "订单号不能为空！", 'data' => 'info_batchcode'];
        }
        $where['info_batchcode']  = array('eq',$postData['info_batchcode']);
        if( !empty($postData['shipping_code']) ){
            $data['shipping_code']  =$postData['shipping_code'];
        }
        if( !empty($postData['shipping_sn']) ){
            $data['shipping_sn']  = $postData['shipping_sn'];
        }
        if( !empty($postData['fare']) ){
            $data['fare']  = $postData['fare'];
        }
        $data['status']  = 3;
        $data['shipping_time'] = date('Y-m-d H:i:s');
        $orderlist=Db::table('orders_info')->where('batchcode',$postData['batchcode'])->where('info_batchcode',$postData['info_batchcode'])->select();

        if( empty($orderlist) ){
            return ['code' => 30052, 'msg' => "没有对应的订单信息！", 'data' => 'orderlist'];
        }
        if( $orderlist['0']['status']!=2){
            return ['code' => 30053, 'msg' => "当前状态不可以发货！", 'data' => $orderlist['0']['status']];
        }

        $orderInfo = Db::table('orders_info')->where('batchcode',$postData['batchcode'])->where('info_batchcode',$postData['info_batchcode'])->find();

        // 查找同步的产品
        $products_synch = Db::table('product')->where(['source_product_id' => $orderInfo['product_id']])->select();
        $prodIds = [];
        foreach ($products_synch as $key => $prod_synch) {
            $prodIds[] = $prod_synch['id'];
        }
        // 查找销售同步的订单详情
        $orderInfoSynch = Db::table('orders_info')
                ->where(['business_id'=>$orderInfo['user_id'],'payment_status' =>1, 'status'=>2])
                ->whereIn('product_id',$prodIds)
                ->find();

        // 启动事务
        Db::startTrans();
        try{
            //跟新订单详情时间
            Db::table('orders_info')->where($where)->update($data);
            // 如果存在销售同步的订单，并且该产品是待发货，则订单状态和物流状态也要相应的改过来同步
            if($orderInfoSynch != null){
                $productSynch = Db::table('product')->where(['id' => $orderInfoSynch['product_id']])->find();
                if($productSynch['is_autodeliver'] == 0){
                    Db::table('orders_info')
                        ->where(['business_id'=>$orderInfo['user_id'],'payment_status' =>1, 'status'=>2])
                        ->whereIn('product_id',$prodIds)
                        ->update($data);
                    Db::table('orders')->where('batchcode',$orderInfoSynch['batchcode'])->update(['status'=>3,'last_time'=> date('Y-m-d H:i:s')]);
                }
            }
            $orders=Db::table('orders_info')->where('batchcode',$postData['batchcode'])->select();
            $ordersstatus=true;
            $total_fare=0;
            foreach ($orders as $key => $value) {
                if ($value['status'] < 3) {
                    $ordersstatus=false;break;
                }
                $total_fare=$total_fare+$value['fare'];
            }
            if($ordersstatus===true){
                Db::table('orders')->where('batchcode',$postData['batchcode'])->update(['total_fare'=>$total_fare,'status'=>3]);
               $up_id = array_column($orders,'product_id');
                Db::table('product')->where(['id'=>['in',$up_id]])->update(['product_state'=>13]);
            }
            // 提交事务
            Db::commit(); 
            return ['code' => 666, 'msg' => "发货成功！", 'data' => true];   
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        
        if ( empty($datas['data']) ) {
            return ['code' => 30050, 'msg' => "操作失败！", 'data' => null];
        }
        
        
    }
    /**
     * 2018-08-16
     * 
     * 刘家腾
     * 
     * 快递模板
     *
     * @param      string  $value  The value
     *
     * @return     array   ( description_of_the_return_value )
     */
    public function shipping_mode()
    {
        $orderlist=Db::table('shipping_mode')->where('state',0)->select();
        if( empty($orderlist) ){
            return ['code' => 666, 'msg' => "没有查询到类似数据！", 'data' => null];
        }else{
            return ['code' => 666, 'msg' => "成功", 'data' => $orderlist];
        }
    }
  


}